// 1. 定义路由组件.

import {i18n, I18N_LANGUAGE_KEY, loadLocaleMessages, setI18nLanguage} from '@/i18n'

import {createRouter, createWebHashHistory} from 'vue-router'
import {useStore} from "@/store/user";

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
    {
        path: '/',
        name:"/",
        component: () => import('@/view/Home.vue')
    },
    {
        path: '/mock-handler',
        name: 'mock-handler',
        component: () => import('@/view/mockHandler/MockHandlerList.vue'),
    },
    {
        path: '/mock-handler-info',
        name: 'mock-handler-info',
        component: () => import('@/view/mockHandler/MockHandlerInfo.vue'),
    },
    {
        path: '/mock-handler-info/:handlerId',
        name: 'mock-handler-info2',
        component: () => import('@/view/mockHandler/MockHandlerInfo.vue'),
    },
    {
        path: '/user',
        name: 'user',
        component: () => import('@/view/user/UserList.vue'),
    },
    {
        path: '/project',
        name: 'project',
        component: () => import('@/view/project/ProjectList.vue'),
    },
    {
        path: '/running-task',
        name: 'running-task',
        component: () => import('@/view/task/runningTask/RunningTaskList.vue'),
    },
    {
        path: '/task-log',
        name: 'task-log',
        component: () => import('@/view/task/taskLog/TaskLogList.vue'),
    },
    {
        path: '/task-log/:taskCode',
        name: 'task-log2',
        component: () => import('@/view/task/taskLog/TaskLogList.vue'),
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/view/login/Login.vue'),
    },
]

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置，但我们在这里
// 暂时保持简单
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHashHistory(),
    routes, // `routes: routes` 的缩写
})

// navigation guards
router.beforeEach(async (to, from, next) => {

    if (to.name === "login") {
        let store = useStore();
        await store.removeUser();
    }

    const paramsLocale = localStorage.getItem(I18N_LANGUAGE_KEY) as string;

    if (!i18n.global.availableLocales.includes(paramsLocale)) {
        await loadLocaleMessages(i18n, paramsLocale)
    }

    setI18nLanguage(i18n, paramsLocale)

    return next()
})

export default router
